package com.ms.service.module.zone;

import java.util.ArrayList;
import java.util.Date;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;

import redis.clients.jedis.Jedis;

import com.ms.game.itembox.AccountItemChangeWay;
import com.ms.game.itembox.ItemStatus;
import com.ms.game.itembox.container.ItemBasic;
import com.ms.game.itembox.db.AccountItemChangeLogModel;
import com.ms.game.itembox.db.AccountItemModel;
import com.ms.game.itembox.db.ItemDAO;
import com.ms.player.Player;
import com.ms.player.PlayerUserType;
import com.ms.service.db.jedis.JedisManager;
import com.ms.service.error.ErrorCode;
import com.ms.service.module.commonsettings.DailySendItemInfo;
import com.ms.service.module.zone.message.DailyLoginSendResponse;
import com.xpec.c4.db.hibernate.manager.HibernateManager;
import com.xpec.c4.game.time.TimeConstants;
import com.xpec.c4.game.time.TimeSys;
import com.xpec.c4.game.utility.GUID;
import com.xpec.c4.game.utility.GUIDFactory;
import com.xpec.c4.game.utility.GUIDType;
import com.xpec.c4.game.utility.GameUtility;
import com.xpec.c4.message.MessageTypes;
import com.xpec.c4.service.message.MessageAction;
import com.xpec.c4.service.module.ModuleName;
import com.xpec.c4.service.module.common.ItemInfoManager;
import com.xpec.c4.service.module.task.TaskAsyncCommand;

public class CheckDailyLoginSendItemAsync extends TaskAsyncCommand{
	
	private static final Log log = LogFactory.getLog(CheckDailyLoginSendItemAsync.class);
		
    private	ArrayList<DailySendItemInfo> dailySendItemInfos;

	private Player player;
	
	private GUID sessionId;

	@Override
	public void asyncExecute() throws Exception {
		DailyLoginSendResponse response = new DailyLoginSendResponse();
		response.setErrorCode(ErrorCode.SUCCESS);
		long loginTime = player.getLastloginTime();

		
		long checkTime = loginTime / 1000;
		ArrayList<DailySendItemInfo> canGetItems = new ArrayList<DailySendItemInfo>();
		// 先確認到底是不是有道具可以拿，如果有才往下做，不然等到標記寫到redis再弄就太慢了
		for (DailySendItemInfo dailySendItemInfo : dailySendItemInfos) {
			if (checkTime < dailySendItemInfo.getStartTime() || (dailySendItemInfo.getEndTime() != -1 && (checkTime >= dailySendItemInfo.getEndTime()))) {
				// 此物品設定時間尚未開始，或是過期了
				continue;
			}
			
			ItemBasic itemBasic = ItemInfoManager.getInstance().getItem(dailySendItemInfo.getId());
			if(itemBasic == null){
				// 找不到此道具，跳過。
				if(log.isErrorEnabled()){
					log.error(dailySendItemInfo.getId() + "not found from ItemInfoManager");
				}
				continue;
			}
			
			canGetItems.add(dailySendItemInfo);
		}
		
		if (canGetItems.size() == 0) {
			//沒有東西可以給
			MessageAction.sendMessage(sessionId, MessageTypes.S_ZONE_CHECK_DAILY_SEND_RESPONSE, response);
			return;
		}

		//去redis 用日期+guid撈
		String today = String.valueOf(GameUtility.getDateOnly(new Date(player.getLastloginTime())).getTime());
		String redisKey = "FNBO_VOUCHER:" + today + "_" + player.getAccountId().toString();
		
		Jedis jedis = JedisManager.getResource(ModuleName.GAMELOBBY);
		boolean get = true;
		try {
			get = jedis.exists(redisKey);
			if (!get) {
				jedis.set(redisKey, "");
				jedis.expire(redisKey, (int) TimeConstants.SECOND_PRE_DAY);
			}
		}
		catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error(GameUtility.getCurMethodName(), e);
			}

			if (jedis != null) {
				JedisManager.returnResource(ModuleName.GAMELOBBY, jedis);
			}

			response.setErrorCode(ErrorCode.DB_OPERATION_FAIL);
			MessageAction.sendMessage(sessionId, MessageTypes.S_ZONE_CHECK_DAILY_SEND_RESPONSE, response);
			return;
		}
		
		JedisManager.returnResource(ModuleName.GAMELOBBY, jedis);

		if (!get) { 
			// 沒有就寫進去 & DC加東西給他 然後回每日獎勵結果給client
			ArrayList<AccountItemModel> accountItemModel = new ArrayList<AccountItemModel>();
			ArrayList<AccountItemChangeLogModel> accountItemChangeLogModels = new ArrayList<AccountItemChangeLogModel>();

			// 將可以送的東西，跑迴圈送出
			for (DailySendItemInfo dailySendItemInfo : canGetItems) {
				// set item model
				GUID sn = GUIDFactory.createUUID(GUIDType.TYPE_ACCOUNT_ITEM);
				String itemId = dailySendItemInfo.getId();
				ItemBasic itemBasic = ItemInfoManager.getInstance().getItem(itemId);
				AccountItemModel model = new AccountItemModel();
				model.setItemId(itemId);
				model.setCount(1);
				model.setSn(sn.toString());
				model.setOwnerAccountId(player.getAccountId().toString());
				model.setStatus(ItemStatus.NORMAL.getId());
				model.setStatusDesc(ItemStatus.NORMAL);
				model.setHasExpireTime(true);

				long expireTime = TimeSys.currentTimeMills() + (itemBasic.getExpireTime() * TimeConstants.MILLI_SECOND_PRE_HOUR);
				Date date = new Date(expireTime);
				date = GameUtility.getDateOnly(date);
				if (date.equals(GameUtility.getDateOnly(new Date()))) {
					date = DateUtils.addDays(date, 1);
				}
				expireTime = date.getTime() / TimeConstants.MILLI_SECOND_PRE_SECOND;
				model.setExpireTime(expireTime);

				accountItemModel.add(model);

				// set log model
				GUID orderId = GUIDFactory.createUUID(GUIDType.TYPE_ACCOUNT_ITEM);
				// 組成 logModel
				AccountItemChangeLogModel itemChangeLogModel = ItemDAO.makeAccountItemChangeLogModel(orderId.toString(), player.getAccountId()
						.toString(), null, null, PlayerUserType.PLAYER, model.getSn(), itemBasic.getItemId(), itemBasic.getName(), 1, 0, 1, AccountItemChangeWay.ADD_RECHARGE, null, null, null, null, null);

				accountItemChangeLogModels.add(itemChangeLogModel);
			}
			
			// 寫game model
			Session session = HibernateManager.txBegin();
			for (AccountItemModel itemModel : accountItemModel) {
				session.save(itemModel);
				session.flush();
			}
			boolean saveModel = HibernateManager.txCommitFailRollbackClearSession();

			if(saveModel){
				// 寫 log model
				for (AccountItemChangeLogModel accountItemChangeLogModel : accountItemChangeLogModels) {
					getModuleServer().saveDbLog(accountItemChangeLogModel);
				}
				
				response.setGetItem(true);
				MessageAction.sendMessage(sessionId, MessageTypes.S_ZONE_CHECK_DAILY_SEND_RESPONSE, response);
				return;
			}
		} 
		
		MessageAction.sendMessage(sessionId, MessageTypes.S_ZONE_CHECK_DAILY_SEND_RESPONSE, response);
	}
	
	@Override
	public void execute() throws Exception {

	}
	
	public void checkCanGetFnboVoucherFromRedis(){
		
	}

	public Player getPlayer() {
		return player;
	}

	public void setPlayer(Player player) {
		this.player = player;
	}

	public GUID getSessionId() {
		return sessionId;
	}

	public void setSessionId(GUID sessionId) {
		this.sessionId = sessionId;
	}
	
	public ArrayList<DailySendItemInfo> getDailySendItemInfos() {
		return dailySendItemInfos;
	}

	public void setDailySendItemInfos(ArrayList<DailySendItemInfo> dailySendItemInfos) {
		this.dailySendItemInfos = dailySendItemInfos;
	}
}
